package org.system.core.controller.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.system.core.annotation.Log;
import org.system.core.common.Result;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.model.LoginUser;
import org.system.core.domain.model.SystemConfiguration;
import org.system.core.enums.BusinessType;
import org.system.core.exception.ServiceException;
import org.system.core.service.system.SysPostService;
import org.system.core.service.system.SysUserService;
import org.system.core.service.system.TokenService;
import org.system.core.utils.EMailUtils;
import org.system.core.utils.PhoneNumberValidator;
import org.system.core.utils.SecurityUtils;
import org.system.core.utils.StringUtils;
import org.system.core.utils.file.FileUploadUtils;
import org.system.core.utils.file.MimeTypeUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author baoRoot
 */
@RestController
@Api(tags = {"个人模块"})
@RequestMapping("/system/user/profile")
public class SysProfileController {

    private static final Logger logger = LoggerFactory.getLogger(SysProfileController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPostService sysPostService;

    @GetMapping
    @ApiOperation("获取个人信息")
    public Result<Map<String, Object>> profile(){
        logger.info("获取个人信息");
        Map<String, Object> map = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        user.setPassword("******");
        map.put("user", user);
        map.put("roles", user.getRoles());
        map.put("dept", user.getDept());
        map.put("post", sysPostService.selectPostList(user.getUserId()));
        return Result.ok(map);
    }

    @PutMapping
    @ApiOperation("修改用户")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    public Result<String> updateProfile(@RequestBody SysUser user){
        logger.info("修改用户: {}", user);
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if(StringUtils.isNotEmpty(user.getPhonenumber()) && !PhoneNumberValidator.isValidPhoneNumber(user.getPhonenumber())){
            throw new ServiceException("手机号格式不正确");
        }
        if(StringUtils.isNotEmpty(user.getEmail()) && !EMailUtils.isValidEmail(user.getEmail())){
            throw new ServiceException("邮箱格式不正确");
        }
        if(sysUserService.checkPhoneUnique(currentUser)) {
            throw new ServiceException("手机号已存在");
        }
        if(sysUserService.checkEmailUnique(currentUser)) {
            throw new ServiceException("邮箱账号已存在");
        }
        if(sysUserService.updateUserProfile(currentUser) <= 0) {
            throw new ServiceException("修改失败，请稍后再试");
        }
        tokenService.setLoginUser(SecurityUtils.getLoginUser());
        return Result.ok();
    }

    @ApiOperation("重置密码")
    @PutMapping("/resetPassword")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    public Result<String> resetPassword(String oldPassword, String newPassword){
        logger.info("修改密码 => 新密码: {}, 旧密码: {}", newPassword, oldPassword);
        String username = SecurityUtils.getLoginUser().getUsername();
        String password = SecurityUtils.getLoginUser().getPassword();
        if(!SecurityUtils.matchesPassword(oldPassword, password)){
            throw new ServiceException("旧密码不正确");
        }
        if(SecurityUtils.matchesPassword(newPassword, password)){
            throw new ServiceException("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if(sysUserService.resetPassword(username, newPassword) <= 0) {
            throw new ServiceException("修改密码失败，请稍后再试");
        }
        SecurityUtils.getLoginUser().getUser().setPassword(newPassword);
        tokenService.setLoginUser(SecurityUtils.getLoginUser());
        return Result.ok();
    }

    @PostMapping("/avatar")
    @ApiOperation("修改用户头像")
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    public Result<String> avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        logger.info("用户修改头像： {}", file);
        if(file.isEmpty()) {
           throw new ServiceException("上传图片失败，请稍后再试");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String avatar = FileUploadUtils.upload(SystemConfiguration.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
        if(!sysUserService.updateUserAvatar(loginUser.getUsername(), avatar)){
            throw new ServiceException("上传图片失败，请稍后再试");
        }
        loginUser.getUser().setAvatar(avatar);
        tokenService.setLoginUser(loginUser);
        return Result.ok(avatar);
    }

}
